angular.module('starter.controllers', [])

//AppController
    .controller('AppCtrl', function ($scope, $rootScope, $state, $ionicModal, $interval, $timeout, Storage, AppService) {
        var initData = JSON.parse(Storage.get("initData"));
        //用来装在初始化参数并显示在页面上
        $scope.initDatas = {};
        if (initData) {
            $scope.initData = initData;
        }
        $rootScope.needInitHome = true;
        // alert(111);
        var stompClient = null;


        //结果都是我看破红尘
        var socket = new SockJS('http://localhost:8888/getConnectToServer');
        stompClient = Stomp.over(socket);
        stompClient.connect({}, function (frame) {
            console.log('Connected:' + frame);
            // stompClient.subscribe('/topic/getResponse', function (response) {
            //     alert(111)
            // });
            stompClient.subscribe('/user/' + initData.user.id + '/queue/getResponse', function (response) {
                alert(222);
            })
        });
        //websocket
        // $scope.connectTest = function () {
        //     var socket = new SockJS('http://localhost:8888/getConnectToServer');
        //     stompClient = Stomp.over(socket);
        //     stompClient.connect({}, function (frame) {
        //         console.log('Connected:' + frame);
        //         // stompClient.subscribe('/topic/getResponse', function (response) {
        //         //     alert(111)
        //         // });
        //         stompClient.subscribe('/user/'+initData.user.id+'/queue/getResponse', function (response) {
        //             alert(222);
        //         })
        //     });
        // }
        $scope.disconnect = function () {
            if (stompClient != null) {
                stompClient.disconnect();
            }
            // setConnected(false);
            console.log('Disconnected');
        }
        $scope.sendName = function () {
            stompClient.send("/welcome", {}, JSON.stringify({'name': "hello"}));
        }
        $scope.showResponse = function (message) {
            alert("message:" + message);
        }
        $scope.showTime = {}

        //用来显示时间
        $scope.showTime = {
            year: "",
            month: "",
            day: "",
            hour: "",
            minutes: "",
            seconds: ""
        }
        $interval(function () {
            var year = new Date().getFullYear()
            var month = new Date().getMonth() + 1;
            var day = new Date().getDate();
            var week = new Date().getDay();
            var hours = new Date().getHours();
            var minutes = new Date().getMinutes();
            var seconds = new Date().getSeconds();
            if (hours < 10) {
                hours = '0' + hour;
            }
            if (minutes < 10) {
                minutes = '0' + minutes;
            }
            if (seconds < 10) {
                seconds = '0' + seconds;
            }
            var weekList = new Array("日", "一", "二", "三", "四", "五", "六");

            $scope.showTime = {
                year: year,
                month: month,
                day: day,
                hours: hours,
                minutes: minutes,
                seconds: seconds,
                week: weekList[week]
            }
        }, 1000);
    })
    //配置页Controller
    .controller('ConfigCtrl', function ($scope, $state, AppService, ConfigService, Storage, $timeout, $ionicPopup, $ionicLoading) {
        $scope.config = {//用来装配置数据
            ip: "",
            port: "",
            pjqNum: ""
        }
        $scope.mValidate = {//用来控制页面显示提示信息
            notNull: "",
            regular: ""
        }
        // alert(111);
        $scope.hasConfig = true;//
        var config = AppService.testConfig();
        if (config == "ok") {
            $timeout(function () {
                $state.go('app.home');
            }, 3000)
        } else {
            $scope.hasConfig = false;
        }

        $scope.saveConfig = function () {
            var ip = $scope.config.ip;
            var port = $scope.config.port;
            var pjqNum = $scope.config.pjqNum;
            if (!ip) {
                $scope.mValidate.notNull = "IP不能为空！";
                return;
            }
            $scope.mValidate.notNull = "";
            var regexp = /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/;
            var valid = regexp.test(ip);
            if (!valid) {//首先必须是 xxx.xxx.xxx.xxx 类型的数字，如果不是，返回false
                $scope.mValidate.regular = "ip填写格式有误！";
                return false;
            } else {
                ip.split('.').every(function (num) {
                    //切割开来，每个都做对比，可以为0，可以小于等于255，但是不可以0开头的俩位数
                    //只要有一个不符合就返回false
                    if (num.length > 1 && num.charAt(0) === '0') {
                        //大于1位的，开头都不可以是‘0’
                        $scope.mValidate.regular = "ip填写格式有误！";
                        return false;
                    } else if (parseInt(num, 10) > 255) {
                        //大于255的不能通过
                        $scope.mValidate.regular = "ip填写格式有误！";
                        return false;
                    }
                    $scope.mValidate.regular = "";
                });
            }
            if (!port) {
                $scope.mValidate.notNull = "端口不能为空！";
                return;
            }
            $scope.mValidate.notNull = "";
            var re = /^([0-9]|[1-9]\d|[1-9]\d{2}|[1-9]\d{3}|[1-5]\d{4}|6[0-4]\d{3}|65[0-4]\d{2}|655[0-2]\d|6553[0-5])$/;
            if (!re.test(port)) {
                $scope.mValidate.regular = "请输入0到65535的整数";
                return false;
            }
            $scope.mValidate.regular = "";
            if (!pjqNum) {
                $scope.mValidate.notNull = "评价器地址不能为空！";
                return;
            }
            $scope.mValidate.notNull = "";
            var g = /^[1-9]*[1-9][0-9]*$/;
            if (!g.test(pjqNum)) {
                $scope.mValidate.regular = "请输入一个正整数";
                return false;
            }
            $scope.mValidate.regular = "";
            $scope.mValidate.notNull = "";
            $scope.connectInfo = "正在连接" + ip + ":" + port;
            ConfigService.testConnectServer(ip, port, pjqNum).then(function (res) {
                console.log(JSON.stringify(res));
                if (!res) {
                    $scope.connectInfo = "连接失败！请联系相关人员";
                    return;
                }
                if (res.state == "ok") {
                    //将正常连接的服务器配置存储到localStorage里面。
                    var config = $scope.config;
                    Storage.set("config", config);

                    $timeout(function () {
                        $scope.connectInfo = "连接成功！";
                        $timeout(function () {
                            $state.go("app.home");
                        }, 1000)
                    }, 1500)
                } else {
                    $timeout(function () {
                        $scope.connectInfo = "连接失败！请联系相关人员";
                    }, 1500)
                }
            })
        }
    })
    //主页Controller
    .controller('HomeCtrl', function ($scope, $state, $compile, $timeout, AppService, Storage) {
        $scope.sendTest = function () {
            // websocket.send("hello world");
        }
        // $scope.m_click = function () {
        //     $state.go("app.call");
        // }
        var initData = JSON.parse(Storage.get("initData"));

        var mediaList = initData.mediaList;
        $scope.noticeList = [];
        $scope.videoList = [];
        $scope.imageList = [];
        angular.forEach(mediaList, function (data, index, array) {
            console.log(JSON.stringify(data));
            if (data.types == "text") {
                $scope.noticeList.push(data);
            }
            if (data.type == "video") {
                if (data.path) {
                    $scope.videoList.push(data);
                }
            }
            if (data.type == 'image') {
                if (data.path) {
                    $scope.imageList.push(data);
                }
            }
        });

        // alert(initData.logo);

        //假数据
        // var gonggao = {
        //     biaoti: "<h1 style='text-align:center'>这是公告</h1>",
        //     neirong: "<p style='font-size:30px;line-height: 30px;'>这是内容<br>另起一行</p>"
        // }
        // var dom_biaoti = gonggao.biaoti;
        // var dom_neirong = gonggao.neirong;
        // var template = angular.element(dom_biaoti + dom_neirong);
        // var mobileDialogElement = $compile(template)($scope);
        // // angular.element('#gonggao').append(mobileDialogElement);
        // angular.element(document).ready(function () {
        //     angular.element(document.querySelector('.gonggao')).append(mobileDialogElement);
        // });

        $scope.goNotice = function () {

        }
    })
    .controller('NoticeDetailCtrl', function ($scope, $state, $stateParams, $compile, Storage) {
        // alert($stateParams.id);
        var initData = JSON.parse(Storage.get("initData"));
        var mediaList = initData.mediaList;
        console.log(JSON.stringify(mediaList));
        //用来显示公告信息
        var notice = {};
        $scope.notice = {
            content: "",
            index: "",
            length: mediaList.length
        };
        angular.forEach(mediaList, function (data, index, array) {
            if (data.id == $stateParams.id) {
                notice = data;
                $scope.notice.content = data;
                $scope.notice.index = index;
            }
        });
        // console.log($scope.notice);
        var gonggao = {
            biaoti: "<h1 style='text-align:center'>" + notice.title + "</h1>",
            neirong: "<p style='font-size:30px;line-height: 30px;'>" + notice.content + "</p>"
        }
        var dom_biaoti = gonggao.biaoti;
        var dom_neirong = gonggao.neirong;
        var template = angular.element(dom_biaoti + dom_neirong);
        var mobileDialogElement = $compile(template)($scope);
        // angular.element('#gonggao').append(mobileDialogElement);
        angular.element(document).ready(function () {
            angular.element(document.querySelector('.gonggao')).append(mobileDialogElement);
        });

        $scope.goNextNotice = function () {
            // alert(index);
            if ($scope.notice.index < (mediaList.length - 1)) {
                angular.element(document.querySelector('.gonggao')).html("");
                // alert(index + "," + mediaList.length);
                $scope.notice.index++;
                var notice = mediaList[$scope.notice.index];
                console.log(notice);
                var gonggao = {
                    biaoti: "<h1 style='text-align:center'>" + notice.title + "</h1>",
                    neirong: "<p style='font-size:30px;line-height: 30px;'>" + notice.content + "</p>"
                }
                var dom_biaoti = gonggao.biaoti;
                var dom_neirong = gonggao.neirong;
                var template = angular.element(dom_biaoti + dom_neirong);
                var mobileDialogElement = $compile(template)($scope);
                // angular.element('#gonggao').append(mobileDialogElement);
                angular.element(document).ready(function () {
                    angular.element(document.querySelector('.gonggao')).append(mobileDialogElement);
                });

            } else {
                alert("最后一页")
            }

        }
    })
    .controller('GongGaoCtrl', function ($scope, $state) {
        $scope.m_click = function () {
            $state.go("app.call");
        }
    })
    //满意度Controller
    .controller('EvalCtrl', function ($scope, $rootScope, $state, $stateParams) {
        $scope.m_click = function () {
            $state.go("app.home");
        }
    })
    //票号呼叫Controller
    .controller('CallCtrl', function ($scope, $rootScope, $state, $stateParams) {
        $scope.ticket = {
            id: '1101',
            ticketNum: 'A001',
            ticketType: "0",//0 普通号，1 预约号
            bizType: "综合业务"
        }
        $rootScope.data = {
            status: 0
        }

        $scope.m_click = function () {

            if ($rootScope.data.status < 3) {
                $rootScope.data.status++;
            } else {
                $state.go("app.eval");
            }
        }
    })
